//
//  XSThumbnailViewController.m
//  AudioVideo
//
//  Created by xueshan1 on 2019/9/16.
//  Copyright © 2019 xueshan1. All rights reserved.
//

#import "XSThumbnailViewController.h"
#import "XSThumbnailCollectionViewCell.h"
#import "XSBigPictureBrowserViewController.h"
#import "XSThumbnailSelectedView.h"

@interface XSThumbnailViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>
{
    BOOL _canBeginPan;//pan开始的点是否可以
    NSInteger _panBeginIndex;
    NSInteger _lastPanIndex;
    BOOL _isSelectOperation; //取消 or 选择
    
    
}
@property(nonatomic,strong)UICollectionView *collectionView;
@property(nonatomic,strong)NSMutableArray *dataArray;

@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) UIView *bline;
@property (nonatomic, strong) UIButton *btnEdit;
@property (nonatomic, strong) UIButton *btnPreView;
@property (nonatomic, strong) UIButton *btnOriginalPhoto;
@property (nonatomic, strong) UILabel *labPhotosBytes;
@property (nonatomic, strong) UIButton *btnDone;
@property(nonatomic,strong)NSMutableArray *selectedArray;
@property(nonatomic,strong)XSThumbnailSelectedView *selectedView;

@end

@implementation XSThumbnailViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = self.albumListModel.title;
    
    if (self.canPanSelectItem) {
        UIPanGestureRecognizer *panG = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panAction:)];
        [self.view addGestureRecognizer:panG];
    }
    
    [self initData];

}
/**
 规则:
 1.手势开始的点是: 已选中状态-> 当前pan是取消操作;
   手势开始的点是: 未选中状态-> 当前pan是选中操作;
 2.操作的点: (开始点index -- 当前点index) 该区间内的所有index
 
 */
#pragma mark - pan select
- (void)panAction:(UIPanGestureRecognizer *)panGes{
    CGPoint locationP = [panGes locationInView:self.collectionView];
    NSIndexPath *curIndexPath = [self.collectionView indexPathForItemAtPoint:locationP];
    NSInteger curIndex = curIndexPath.item;
    XSThumbnailCollectionViewCell *curCell = (XSThumbnailCollectionViewCell *)[self.collectionView cellForItemAtIndexPath:curIndexPath];
    if (curCell == nil) {
        return;
    }
//    NSLog(@"locationP: %@ curIndex: %ld :%@", NSStringFromCGPoint(locationP), curIndex , curCell);

    if (panGes.state == UIGestureRecognizerStateBegan) {
//        _canBeginPan = curIndex == 0 ? NO : YES;
        _canBeginPan = YES;

        _panBeginIndex = curIndex;
        _lastPanIndex = curIndex;

        XSPhotoModel *model = self.dataArray[curIndex];
        _isSelectOperation = model.isSelected?YES:NO;
        
    }else if (panGes.state == UIGestureRecognizerStateChanged){
        if (!_canBeginPan ||
            curIndex == _lastPanIndex) {
            return;
        }
        _lastPanIndex = curIndex;
        NSInteger minIndex = MIN(_panBeginIndex, curIndex);
        NSInteger maxIndex = MAX(_panBeginIndex, curIndex);
        
//        NSLog(@"_panBeginIndex: %ld curIndex: %ld", _panBeginIndex, curIndex);
        for (NSInteger i = minIndex; i<=maxIndex; i++) {
            XSPhotoModel *model = self.dataArray[i];
            model.selected = !_isSelectOperation;
            
            NSIndexPath *selectPath = [NSIndexPath indexPathForRow:i inSection:0];
            XSThumbnailCollectionViewCell *selectCell = (XSThumbnailCollectionViewCell *)[self.collectionView cellForItemAtIndexPath:selectPath];
            if (selectCell) {
                selectCell.selectBtn.selected = model.selected;
            }
            
        }
        
        
    }else if (panGes.state == UIGestureRecognizerStateEnded ||
              panGes.state == UIGestureRecognizerStateCancelled||
              panGes.state == UIGestureRecognizerStatePossible){
        
        [self.selectedArray removeAllObjects];
        for (XSPhotoModel *model in self.dataArray) {
            if (model.isSelected) {
                [self.selectedArray addObject:model];
            }
        }
 
        [self.btnDone setTitle:[NSString stringWithFormat:@"确定(%ld)",self.selectedArray.count] forState:UIControlStateNormal];

        [self.selectedView.dataArray removeAllObjects];
        [self.selectedView.dataArray addObjectsFromArray:self.selectedArray];
        [self.selectedView reloadData];
        
    }
    
    
    
}



- (void)initData{
    [self.dataArray removeAllObjects];
    
    if (self.albumListModel) {
        [self.dataArray addObjectsFromArray:self.albumListModel.models];
        [self.collectionView reloadData];
        
    }else{
        [XSPhotosManager getCameraRollAlbumListAllowSelectVideo:self.selectVideo allowSelectImage:!self.selectVideo complete:^(XSAlbumListModel *  albumModel) {
            self.albumListModel = albumModel;
            self.title = albumModel.title;
            
            [self.dataArray addObjectsFromArray:albumModel.models];
            
            [self.collectionView reloadData];
        }];
    }

    
}

- (void)setupUI{
//    self.collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithColor:[UIColor whiteColor] highColor:[UIColor lightGrayColor] target:self action:@selector(cancleBtnClick) title:@"取消"];
 
    
    WeakSelf
    _selectedView = [[XSThumbnailSelectedView alloc]initWithFrame:CGRectMake(0, self.collectionView.bottom, kWidth, 150)];
    [self.view addSubview:_selectedView];
    _selectedView.isVideo = self.selectVideo;
    _selectedView.clickNextBtnBlock = ^{
        [weakSelf doneBtnClick];
    };
    _selectedView.clickDeleteBtnBlock = ^(XSPhotoModel * _Nonnull photoModel) {
        photoModel.selected = NO;
        [weakSelf.collectionView reloadData];
    };
}

- (UICollectionView *)collectionView{
    if (!_collectionView) {
        UICollectionViewFlowLayout *fl = [[UICollectionViewFlowLayout alloc]init];
        NSInteger colCount = 4;
        CGFloat space = 2;
        CGFloat wid = (kWidth - space * (colCount - 1))/colCount;
        fl.itemSize = CGSizeMake(wid, wid);
        fl.minimumLineSpacing = space;
        fl.minimumInteritemSpacing  = space;
        fl.sectionInset = UIEdgeInsetsMake(3, 0, 3, 0);
        
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, NavHFit, kWidth, kHeight - NavHFit - 150) collectionViewLayout:fl];
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.bounces = NO;
        [_collectionView registerNib:[UINib nibWithNibName:@"XSThumbnailCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"cellID"];
        [self.view addSubview:_collectionView];
    }
    return _collectionView;
}

- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray arrayWithCapacity:5];
    }
    return _dataArray;
}
- (NSMutableArray *)selectedArray{
    if (!_selectedArray) {
        _selectedArray = [NSMutableArray arrayWithCapacity:5];
    }
    return _selectedArray;
}

- (void)cancleBtnClick{
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
    
}

- (void)doneBtnClick{
    [self.navigationController dismissViewControllerAnimated:YES completion:^{
        
        [XSPhotosManager shareInstance].selectedPhtotosBlock(self.selectedArray);
    }];
   
}

#pragma mark - collectionView
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    XSThumbnailCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellID" forIndexPath:indexPath];
    
    cell.photoModel = self.dataArray[indexPath.item];
    
    __weak typeof(cell)weakCell = cell;
    cell.selectBtnClickedBlock = ^(BOOL isSelected) {
        __strong typeof(weakCell)strongCell = weakCell;
        if (!isSelected) {
            if ([self canSelectModel]) {
                strongCell.selectBtn.selected = YES;
                strongCell.photoModel.selected = YES;
                [self.selectedArray addObject:strongCell.photoModel];
                [self.selectedView.dataArray addObject:strongCell.photoModel];
                [self.selectedView reloadData];

            }
        }else{
            strongCell.selectBtn.selected = NO;
            strongCell.photoModel.selected = NO;
            [self.selectedArray removeObject:strongCell.photoModel];
            [self.selectedView.dataArray removeObject:strongCell.photoModel];
            [self.selectedView reloadData];
        }
       
        [self.btnDone setTitle:[NSString stringWithFormat:@"确定(%ld)",self.selectedArray.count] forState:UIControlStateNormal];

    };
    return cell;
}

- (BOOL)canSelectModel{
    if (self.selectedArray.count >= self.maxSelectCount ) {
        ShowToastLong(@"最多选择%ld个",self.maxSelectCount);
        return NO;
    }
    
    return YES;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    
    XSPhotoModel *modle = self.dataArray[indexPath.row];
    if (modle.type == XSAssetMediaTypeVideo) {
        //->视频编辑
        
    }else{
        //->图片编辑
          
    }
    
    XSBigPictureBrowserViewController *browserVC = [[XSBigPictureBrowserViewController alloc] initWithNibName:@"XSBigPictureBrowserViewController" bundle:nil];
    browserVC.dataArray = self.dataArray;
    browserVC.selectIndex = indexPath.item;
    browserVC.maxSelectCount = self.maxSelectCount;
    browserVC.canEdit = NO;
    [self.navigationController pushViewController:browserVC animated:YES];
    
}



@end
